package com.example.edu.service.impl;

import com.example.edu.entity.Chapter;
import com.example.edu.entity.Video;
import com.example.edu.entity.course.EduChapter;
import com.example.edu.entity.course.EduVideo;
import com.example.edu.exceptionhandler.HeartEduException;
import com.example.edu.mapper.ChapterMapper;
import com.example.edu.service.ChapterService;
import com.example.edu.service.VideoService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2020-07-02
 */
@Service
public class ChapterServiceImpl extends ServiceImpl<ChapterMapper, Chapter> implements ChapterService {

	@Autowired
	private VideoService videoService;
	
	@Override
	public List<EduChapter> getAllChapterVideo(String courseId) {
		// TODO Auto-generated method stub
		QueryWrapper<Chapter> chapterWrapper = new QueryWrapper<>();
		chapterWrapper.eq("course_id", courseId);
		List<Chapter> chapters = baseMapper.selectList(chapterWrapper);
		
		QueryWrapper<Video> videoWrapper = new QueryWrapper<Video>();
		videoWrapper.eq("course_id", courseId);
		List<Video> videos = videoService.list(videoWrapper);
		List<EduChapter> eduChapters = new ArrayList<EduChapter>();
		for (int i = 0; i < chapters.size(); i++) {
			EduChapter eduChapter = new EduChapter();
			Chapter chapter = chapters.get(i);
			BeanUtils.copyProperties(chapter, eduChapter);
			eduChapters.add(eduChapter);
			List<EduVideo> eduVideos = new ArrayList<EduVideo>();
			for (int j = 0; j < videos.size(); j++) {
				Video video = videos.get(j);
				if(video.getChapterId().equals(chapter.getId())) {
					EduVideo eduVideo = new EduVideo();
					BeanUtils.copyProperties(video, eduVideo);
					eduVideos.add(eduVideo);
				}
			}
			eduChapter.setChildren(eduVideos);
		}
		return eduChapters;
	}

	@Override
	public void deleteById(String id) {
		// TODO Auto-generated method stub
		QueryWrapper<Video> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("chapter_id", id);

		int count = videoService.count(queryWrapper);
		if(count>0) {
			throw new HeartEduException(20001,"该章节下有小节信息，删除失败");
		}else {
			baseMapper.deleteById(id);
		}
	}

}
